package com.smartlazy.sequence.server.service;

import com.smartlazy.sequence.common.biz.util.DateUtil;
import com.smartlazy.sequence.mysql.core.mapper.SysSequenceMapper;
import com.smartlazy.sequence.mysql.core.mysql.MysqlSeqRangeMgr;
import com.smartlazy.sequence.mysql.core.sequence.MysqlRangeSequence;
import com.smartlazy.sequence.redis.core.sequence.RedisRangeSequence;
import com.smartlazy.sequence.redis.core.sequence.RedisSequence;
import com.smartlazy.sequence.core.sequence.Sequence;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author howe
 */
@Service
public class IDServer {

    @Autowired
    private Sequence nextMerchantId;

    @Autowired
    private RedisSequence defaultSequence;

    @Autowired
    private RedisRangeSequence nextAccId;

    @Autowired
    private MysqlRangeSequence nextMysqlId;

    @Autowired
    private SysSequenceMapper sysSequenceMapper;

    public String nextMerchantId() throws Exception {
        String yyyyMMDD = DateUtil.getDays();
        return yyyyMMDD + String.format("%08d", nextMerchantId.nextValue());
    }

    public String nextSerNo() throws Exception {
        defaultSequence.setName("ser_no_" + DateUtil.getDays());
        long next = defaultSequence.nextValue();
        return "ser_"+ DateUtil.sdf_time1.format(new Date())+ String.format("%06d", next);
    }

    public String nextAccId(String name) throws Exception {
        if (StringUtils.isEmpty(name)) {
            nextAccId.setName("acc_" + DateUtil.getDays());
        } else {
            nextAccId.setName(name);
        }
        long next = nextAccId.nextValue();
        return "acc_"+ DateUtil.sdf_time1.format(new Date())+ String.format("%06d", next);
    }

    public String nextMysqlId(String name) throws Exception {
        if (StringUtils.isEmpty(name)) {
            nextMysqlId.setName("mysql_" + DateUtil.getDays());
        } else {
            nextMysqlId.setName(name);
        }
        MysqlSeqRangeMgr mysql = (MysqlSeqRangeMgr)nextMysqlId.getSeqRangeMgr();
        mysql.setSysSequenceMapper(sysSequenceMapper);
        long next = nextMysqlId.nextValue();
        return "acc_"+ DateUtil.sdf_time1.format(new Date())+ String.format("%06d", next);
    }
}
